/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.bfpro.wot.stat;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Stroke;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.JsonObject;
import javax.swing.JFrame;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

/**
 *
 * @author admin
 */
public class StatGrid extends JFrame {
    /**
     * Creates new form StatGrid
     */
    public StatGrid() throws ClassNotFoundException, SQLException {
        initComponents();

        Database db = new Database();
        lbl_RecordCount.setText(Integer.toString(db.getRecCount()));

        // db.getCollection();
        List<StatData> statData = db.getArrayList();
        TableModel model = new MyTableModel(statData);
        jTable1.setModel(model);
        // Установим ширину столбцов
        jTable1.getColumnModel().getColumn(0).setWidth(40);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setWidth(130);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(130);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(130);
        jTable1.getColumnModel().getColumn(1).setResizable(false);

        jTable1.getSelectionModel().addListSelectionListener(new MySelection());
        jTable1.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // Строим график
        DefaultCategoryDataset  dataset1 = new DefaultCategoryDataset();
        DefaultCategoryDataset  dataset2 = new DefaultCategoryDataset();
        DefaultCategoryDataset  dataset3 = new DefaultCategoryDataset();
        for (StatData itemData : statData)
        {
            dataset1.addValue(itemData.get_StatValues().avg_xp(), "Ср.опыт за бой", itemData.getDate());

            dataset2.addValue(itemData.get_StatValues().winPrc(),"% побед",itemData.getDate());
            dataset2.addValue(itemData.get_StatValues().survivedPrc(),"% выживания",itemData.getDate());
            dataset2.addValue(itemData.get_StatValues().hitsPrc(),"% попаданий",itemData.getDate());

            dataset3.addValue(itemData.get_StatValues().destroyedPrc(),"Уничтожил за бой",itemData.getDate() );
            dataset3.addValue(itemData.get_StatValues().killMeter(),"Уничтожил/убит",itemData.getDate() );
            dataset3.addValue(itemData.get_StatValues().damageMeter(), "Урон нанес/получил", itemData.getDate());
        }
        Stroke lineStroke = new BasicStroke(3);
        CategoryItemRenderer renderer;
        // 1
        JFreeChart chart1 = ChartFactory.createLineChart("Опыт", null, null, dataset1,
                    PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot1 = (CategoryPlot)chart1.getPlot();
        NumberAxis rangeAxis1 = (NumberAxis)plot1.getRangeAxis();
        rangeAxis1.setFixedAutoRange(20);
        rangeAxis1.setUpperBound(270);
        ChartPanel chartPanel1 = new ChartPanel(chart1);
        renderer = plot1.getRenderer();
        renderer.setSeriesStroke(0, lineStroke);
        panGraph.add(chartPanel1);
        // 2
        JFreeChart chart2 = ChartFactory.createLineChart("Победы и выживание", null, null, dataset2,
                    PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot2 = (CategoryPlot)chart2.getPlot();
        NumberAxis rangeAxis2 = (NumberAxis)plot2.getRangeAxis();
        rangeAxis2.setFixedAutoRange(20);
        rangeAxis2.setUpperBound(50);
        ChartPanel chartPanel2 = new ChartPanel(chart2);
        renderer = plot2.getRenderer();
        renderer.setSeriesStroke(0, lineStroke);
        renderer.setSeriesStroke(1, lineStroke);
        renderer.setSeriesStroke(2, lineStroke);
        panGraph.add(chartPanel2);
        // 3
        JFreeChart chart3 = ChartFactory.createLineChart("Kill-meter", null, null, dataset3,
                    PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot3 = (CategoryPlot)chart3.getPlot();
        NumberAxis rangeAxis3 = (NumberAxis)plot3.getRangeAxis();
        rangeAxis3.setFixedAutoRange(0.7);
        rangeAxis3.setUpperBound(1.3);
        ChartPanel chartPanel3 = new ChartPanel(chart3);
        renderer = plot3.getRenderer();
        renderer.setSeriesStroke(0, lineStroke);
        renderer.setSeriesStroke(1, lineStroke);
        renderer.setSeriesStroke(2, lineStroke);
        panGraph.add(chartPanel3);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        pan_MainInfo = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        lbl_Date = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lbl_AllFight = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lbl_AvgSkill = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lbl_WinPercent = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lbl_DamageDealt = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        lbl_DamageReceived = new javax.swing.JLabel();
        Выжил = new javax.swing.JLabel();
        lbl_SurvivePercent = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lbl_Destroy = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        lbl_KillVsLost = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        lbl_DamageMeter = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        lbl_AvgShots = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        lbl_HitDamage = new javax.swing.JLabel();
        pan_Footer = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lbl_RecordCount = new javax.swing.JLabel();
        panGraph = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Статистика");
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(800, 600));
        setPreferredSize(new java.awt.Dimension(800, 600));
        getContentPane().setLayout(new java.awt.CardLayout());

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.PAGE_AXIS));

        jScrollPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(800, 400));

        jScrollPane1.setViewportView(jTable1);

        jPanel1.add(jScrollPane1);

        pan_MainInfo.setMaximumSize(new java.awt.Dimension(32767, 800));
        pan_MainInfo.setMinimumSize(new java.awt.Dimension(800, 60));
        pan_MainInfo.setPreferredSize(new java.awt.Dimension(800, 80));
        pan_MainInfo.setLayout(new java.awt.GridLayout(4, 8, 5, 5));

        jLabel2.setText("Дата:");
        jLabel2.setPreferredSize(new java.awt.Dimension(20, 14));
        pan_MainInfo.add(jLabel2);

        lbl_Date.setText("--");
        pan_MainInfo.add(lbl_Date);

        jLabel4.setText("Проведено боев:");
        jLabel4.setPreferredSize(new java.awt.Dimension(20, 14));
        pan_MainInfo.add(jLabel4);

        lbl_AllFight.setText("--");
        pan_MainInfo.add(lbl_AllFight);

        jLabel3.setText("Ср.опыт:");
        jLabel3.setPreferredSize(new java.awt.Dimension(20, 14));
        pan_MainInfo.add(jLabel3);

        lbl_AvgSkill.setText("--");
        pan_MainInfo.add(lbl_AvgSkill);

        jLabel5.setText("% побед:");
        pan_MainInfo.add(jLabel5);

        lbl_WinPercent.setText("--");
        pan_MainInfo.add(lbl_WinPercent);

        jLabel6.setText("Ср. урон за бой:");
        pan_MainInfo.add(jLabel6);

        lbl_DamageDealt.setText("--");
        pan_MainInfo.add(lbl_DamageDealt);

        jLabel7.setText("Ср.урон получил:");
        pan_MainInfo.add(jLabel7);

        lbl_DamageReceived.setText("--");
        pan_MainInfo.add(lbl_DamageReceived);

        Выжил.setText("% выживания:");
        pan_MainInfo.add(Выжил);

        lbl_SurvivePercent.setText("--");
        pan_MainInfo.add(lbl_SurvivePercent);

        jLabel8.setText("Уничтожил за бой:");
        pan_MainInfo.add(jLabel8);

        lbl_Destroy.setText("--");
        pan_MainInfo.add(lbl_Destroy);

        jLabel9.setText("Уничтожил/убит:");
        pan_MainInfo.add(jLabel9);

        lbl_KillVsLost.setText("--");
        pan_MainInfo.add(lbl_KillVsLost);

        jLabel10.setText("Нанес повреждений/Получил:");
        pan_MainInfo.add(jLabel10);

        lbl_DamageMeter.setText("--");
        pan_MainInfo.add(lbl_DamageMeter);

        jLabel11.setText("Ср.выстрелов за бой:");
        pan_MainInfo.add(jLabel11);

        lbl_AvgShots.setText("--");
        pan_MainInfo.add(lbl_AvgShots);

        jLabel13.setText("Ср. урон при попадании:");
        pan_MainInfo.add(jLabel13);

        lbl_HitDamage.setText("--");
        pan_MainInfo.add(lbl_HitDamage);

        jPanel1.add(pan_MainInfo);

        pan_Footer.setLayout(new javax.swing.BoxLayout(pan_Footer, javax.swing.BoxLayout.LINE_AXIS));

        jLabel1.setLabelFor(lbl_RecordCount);
        jLabel1.setText("Кол-во записей:");
        jLabel1.setToolTipText("");
        pan_Footer.add(jLabel1);

        lbl_RecordCount.setText("0");
        pan_Footer.add(lbl_RecordCount);

        jPanel1.add(pan_Footer);

        jTabbedPane1.addTab("Данные", jPanel1);

        panGraph.setLayout(new javax.swing.BoxLayout(panGraph, javax.swing.BoxLayout.LINE_AXIS));
        jTabbedPane1.addTab("Графики", panGraph);

        getContentPane().add(jTabbedPane1, "card2");
        jTabbedPane1.getAccessibleContext().setAccessibleName("Tab1");
        jTabbedPane1.getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])  {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(StatGrid.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(StatGrid.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(StatGrid.class.getName()).log(Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            Logger.getLogger(StatGrid.class.getName()).log(Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new StatGrid().setVisible(true);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(StatGrid.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(StatGrid.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

    }

public class MySelection implements ListSelectionListener {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            int allFights = 0;
            float winPercent = 0;
            int avgSkill = 0;
            int allSurvived = 0;        // Выжил
            float survivedPrc = 0.0f;
            int allDestroyed = 0;       // Уничтожил
            float destroyedPrc = 0.0f;
            int beLost = 0;
            float damagePut = 0;
            float damageGet = 0;
            float damageMeter = 0;

            int prev_allFights = 0;
            float prev_winPercent = 0;
            int prev_avgSkill = 0;
            int prev_allSurvived = 0;
            float prev_survivedPrc = 0.0f;
            int prev_allDestroyed = 0;
            float prev_destroyedPrc = 0.0f;
            int prev_beLost = 0;
            float prev_damagePut = 0;
            float prev_damageGet = 0;
            float prev_damageMeter = 0;
            float prev_avgShots = 0;
            float prev_hitDamage = 0;

            StatValues prev_values;

            lbl_Date.setText(jTable1.getValueAt(jTable1.getSelectedRows()[0],1).toString());
            StatValues values = new StatValues(jTable1.getValueAt(jTable1.getSelectedRows()[0],2).toString());


            if (jTable1.getSelectedRow() == 0) {
                prev_avgSkill = 0;
                prev_winPercent = 0;
            } else {
                prev_values = new StatValues(jTable1.getValueAt(jTable1.getSelectedRows()[0]-1,2).toString());
                prev_allFights = prev_values.battles_count();
                prev_avgSkill = prev_values.avg_xp();
                prev_winPercent = prev_values.winPrc();
                prev_allSurvived = prev_values.survived_battles();
                prev_survivedPrc = prev_values.survivedPrc();
                prev_allDestroyed = prev_values.destroyed();
                prev_destroyedPrc = prev_values.destroyedPrc();
                prev_beLost = prev_allFights - prev_allSurvived;
                prev_damagePut = prev_values.avg_damage();
                prev_damageGet = prev_values.avg_damage_received();
                prev_damageMeter = prev_values.damageMeter();
                prev_avgShots = prev_values.avg_shots();
                prev_hitDamage = prev_values.avg_hitDamage();
            }

            allFights = values.battles_count();
            winPercent = values.winPrc();
            avgSkill = values.avg_xp();
            allSurvived = values.survived_battles();
            survivedPrc = values.survivedPrc();
            allDestroyed = values.destroyed();
            destroyedPrc = values.destroyedPrc();
            beLost = allFights - allSurvived;
            damagePut = values.avg_damage();
            damageGet = values.avg_damage_received();
            damageMeter = values.damageMeter();

            DecimalFormat df = new DecimalFormat("0.000");
            lbl_AllFight.setText(Integer.toString(allFights));
            lbl_AvgSkill.setText(Integer.toString(avgSkill) + " (" + Integer.toString(avgSkill-prev_avgSkill) +  ")");
            lbl_WinPercent.setText(df.format(winPercent)+ " (" + df.format(winPercent-prev_winPercent) +  ")");
            lbl_DamageDealt.setText(df.format(damagePut)+ " (" + df.format(damagePut-prev_damagePut) +  ")");
            lbl_DamageReceived.setText(df.format(damageGet)+ " (" + df.format(damageGet-prev_damageGet) +  ")");
            lbl_SurvivePercent.setText(df.format(survivedPrc)+ " (" + df.format(survivedPrc-prev_survivedPrc) +  ")");
            lbl_Destroy.setText(df.format(destroyedPrc)+ " (" + df.format(destroyedPrc-prev_destroyedPrc) +  ")");
            lbl_KillVsLost.setText(df.format((float)allDestroyed / (float)beLost) + " (" + df.format((float)allDestroyed / (float)beLost-(float)prev_allDestroyed / (float)prev_beLost) +  ")");
            lbl_DamageMeter.setText(df.format(damageMeter) + " (" + df.format(damageMeter - prev_damageMeter) + ")");
            lbl_AvgShots.setText(df.format(values.avg_shots()) + " (" + df.format(values.avg_shots() - prev_avgShots) +  ")");
            lbl_HitDamage.setText(df.format(values.avg_hitDamage()) + " (" + df.format(values.avg_hitDamage() - prev_hitDamage) + ")");
            // System.out.println(values.getData().toString());
        }
}

public class MyTableModel implements TableModel {
        private Set<TableModelListener> listeners = new HashSet<TableModelListener>();
        private List<StatData> statData;

        public MyTableModel(List<StatData> statData) {
            this.statData = statData;
        }

        public void addTableModelListener(TableModelListener listener) {
            listeners.add(listener);
        }

        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }

        public int getColumnCount() {
            return 3;
        }

        public String getColumnName(int columnIndex) {
            switch (columnIndex) {
            case 0:
                return "ID";
            case 1:
                return "Дата";
            case 2:
                return "Содержание";
            }
            return "";
        }

        public int getRowCount() {
            return statData.size();
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            StatData statItem = statData.get(rowIndex);
            switch (columnIndex) {
            case 0:
                return statItem.getId();
            case 1:
                return statItem.getDateTime();
            case 2:
                return statItem.getData();
            }
            return "";
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        public void removeTableModelListener(TableModelListener listener) {
            listeners.remove(listener);
        }

        public void setValueAt(Object value, int rowIndex, int columnIndex) {

        }
    }




    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbl_AllFight;
    private javax.swing.JLabel lbl_AvgShots;
    private javax.swing.JLabel lbl_AvgSkill;
    private javax.swing.JLabel lbl_DamageDealt;
    private javax.swing.JLabel lbl_DamageMeter;
    private javax.swing.JLabel lbl_DamageReceived;
    private javax.swing.JLabel lbl_Date;
    private javax.swing.JLabel lbl_Destroy;
    private javax.swing.JLabel lbl_HitDamage;
    private javax.swing.JLabel lbl_KillVsLost;
    private javax.swing.JLabel lbl_RecordCount;
    private javax.swing.JLabel lbl_SurvivePercent;
    private javax.swing.JLabel lbl_WinPercent;
    private javax.swing.JPanel panGraph;
    private javax.swing.JPanel pan_Footer;
    private javax.swing.JPanel pan_MainInfo;
    private javax.swing.JLabel Выжил;
    // End of variables declaration//GEN-END:variables
}
